package io.renren.modules.mapp.service.impl;


import com.alibaba.fastjson.JSONObject;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.mapp.Constants;
import io.renren.modules.mapp.entity.UserInfo;
import io.renren.modules.mapp.exception.AuthorizationAPIException;
import io.renren.modules.mapp.exception.ConfigurationException;
import io.renren.modules.mapp.exception.LoginServiceException;
import io.renren.modules.mapp.service.LoginService;
import io.renren.modules.mapp.utils.AuthorizationAPI;

import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2017/7/31 0031.
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService{

    public JSONObject login(String code,String encryptedData,String iv)  {

        AuthorizationAPI api = new AuthorizationAPI();
        JSONObject loginResult=prepareResponseJson();
        try {
            loginResult = api.login(code, encryptedData, iv);
        } catch (AuthorizationAPIException apiError) {
            LoginServiceException error = new LoginServiceException(Constants.ERR_LOGIN_FAILED, apiError.getMessage(), apiError);
            throw error;
        } catch (ConfigurationException e) {
            throw new RRException(e.getMessage(),500,e);
        }

        return loginResult;
    }

    JSONObject prepareResponseJson() {
        JSONObject json = new JSONObject();
        json.put(Constants.WX_SESSION_MAGIC_ID, 1);
        return json;
    }

    /**
     * 检查当前请求的会话状态
     * @return 如果包含可用会话，将会返回会话对应的用户信息
     * */
    public UserInfo check(String id, String skey) throws LoginServiceException, ConfigurationException {

        AuthorizationAPI api = new AuthorizationAPI();
        JSONObject checkLoginResult = null;
        try {
            checkLoginResult = api.checkLogin(id, skey);
        } catch (AuthorizationAPIException apiError) {
            String errorType = Constants.ERR_CHECK_LOGIN_FAILED;
            if (apiError.getCode() == 60011 || apiError.getCode() == 60012) {
                errorType = Constants.ERR_INVALID_SESSION;
            }
            LoginServiceException error = new LoginServiceException(errorType, apiError.getMessage(), apiError);
            //writeJson(getJsonForError(error));
            throw error;
        }
        JSONObject userInfo = null;
        userInfo = checkLoginResult.getJSONObject("user_info");
        return UserInfo.BuildFromJson(userInfo);
    }



}
